<template>
  <div class="pages subcardedit">
    <div class="pageLevel">
      <!-- 表单内容 -->
      <div class="from_main">
        <!-- <p>基础信息</p> -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
           <el-form-item label-width="0px">
            <el-button type="primary" size="small" v-if="showTab=='1' || showTab=='3'" @click="submitForm('ruleForm')">保 存</el-button>
            <el-button @click="resetForm('ruleForm')" size="small">取 消</el-button>
          </el-form-item>
           <el-form-item label="次卡名称" prop="ciname">
            <el-input :disabled="cikic" v-model="ruleForm.ciname" clearable placeholder="输入次卡名称" maxlength="30" size="small"></el-input>
            <span>(4～30个字)</span>
          </el-form-item>
          <el-form-item label="参与服务" prop="participation">
            <template>
              <el-button :disabled="cikic" type="primary" size="small" @click="changeservice()">选择服务</el-button>
              <div class="tableMain" style="width:800px">
                <el-table :data="tableDatas" stripe style="width: 100%">
                  <el-table-column prop="name" label="服务名称" align="center">
                  </el-table-column>
                  <el-table-column prop="serviceTime" label="时长" align="center">
                  </el-table-column>
                  <el-table-column prop="price" align="center" label="价格">
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-form-item>
          <el-form-item label='单次服务包括的商品' label-width='150px' v-if='serviceWidthGoods.length > 0'>
            <el-table :data="serviceWidthGoods" border style="width: 750px" class='table-service' max-height='250px'>
              <el-table-column label="序号" width="80" type='index' align='center'></el-table-column>
              <el-table-column prop='goodsName' label="商品名称" width='180' align='center'></el-table-column>
              <el-table-column prop="goodsCode" label="商品条码" width="180" align='center'>
              </el-table-column>
              <el-table-column prop="primaryClassify" label="分类" align='center'>
              </el-table-column>
              <el-table-column prop="goodsNum" label="数量" align='center' width='80'>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="次卡次数" prop="limitofuse">
              <el-input clearable placeholder="如：20" size="small" v-model="ruleForm.limitofuse">
                <template slot="append">次</template>
              </el-input>
            </el-form-item>
          <el-form-item label="次卡会员价" prop="climoney">
            <el-input v-model="ruleForm.climoney" clearable placeholder="如：99.99" size="small" @keyup.native='replace(ruleForm,"climoney")'>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="次卡原价" prop="originPrice">
              <el-input clearable placeholder="如：99.99" size="small" v-model="ruleForm.originPrice" @keyup.native='replace(ruleForm,"originPrice")'>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          <el-form-item label="是否提成" prop="serticheng" v-if="!(soUrce !=5&&isShop==0)">
            <el-radio-group v-model="ruleForm.isCommission">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
            <template>
              <div v-show="ruleForm.isCommission === '1'">
                <el-select v-model="ruleForm.commissionType" size="small">
                  <el-option label="比例提成" value="0"></el-option>
                  <el-option label="固定提成" value="1"></el-option>
                </el-select>
                <el-input v-model="ruleForm.number" size="small"></el-input>
                <span v-if="ruleForm.commissionType == 0">%</span>
                <span v-else>元</span>
              </div>
            </template>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group :disabled="storeyin" v-model="ruleForm.status">
              <el-radio label="0">上架</el-radio>
              <el-radio label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
               <el-form-item label="有效期" prop="termvalidity" style="margin-top:20px;">
            <el-input v-model="ruleForm.termvalidity" maxlength="8" clearable placeholder="正整数" size="small">
              <template slot="append">个月</template>
            </el-input>
            <span>（正整数）</span>
          </el-form-item>
          <div v-if="isApp">
            <p class="jichu">购买须知</p>
            <el-form-item label="适用人数" prop="fitPerNum">
              <el-select v-model="ruleForm.fitPerNum" placeholder="请选择" size="small">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
             <span>（人数选择）</span>
            </el-form-item>

            <el-form-item label="预约信息" prop="appointmentMsg">
              <el-input clearable placeholder="" maxlength="30" size="small" v-model="ruleForm.appointmentMsg"></el-input>
              <span>(4~30字)</span>
            </el-form-item>
            <el-form-item label="规则提醒" prop="ruleHint">
              <el-input clearable placeholder="" maxlength="30" size="small" v-model="ruleForm.ruleHint"></el-input>
              <span>(4~30字)</span>
            </el-form-item>
          </div>
          <el-form-item label="除外日期" prop="checkboxGroup">
            <el-checkbox-group v-model="ruleForm.checkboxGroup" size="medium">
              <el-checkbox-button v-for="city in cities" :label="city" :key="city" style="margin-left:0px;">{{city}}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>

              <el-form-item label="可用时间段">
            <span>(不填写则默认为任何时间段可用)</span>
          </el-form-item>
          <el-form-item label="">
             <el-time-picker v-model="ruleForm.startTime" :default-value="defauleTime" placeholder="任意时间点" size="small" style="width: 150px" value-format="HH:mm:ss"></el-time-picker>
             <el-time-picker v-model="ruleForm.endTime" :default-value="defauleTime" placeholder="任意时间点" size="small" style="width: 150px" value-format="HH:mm:ss"></el-time-picker>
             <el-button type="primary" size="small" @click="onAddTime" :disabled="timeList.length >= 2">添加可用时间</el-button>
          </el-form-item>
          <el-form-item label="">
              <el-tag v-for="(tag,key) in timeList" :key="key" closable @close="handleClose(tag)"> {{tag.startTime}}-{{tag.endTime}}</el-tag>
          </el-form-item>
        </el-form>
      </div>
      <!-- 选择服务弹窗 -->

      <el-dialog title="选择服务" :visible.sync="dialogVisiblew" width="50%" class="addshopname shopname">
        <i class="el-icon-close icon" @click="serviceicon"></i>
        <div class="prices">
          <div class="tableMain">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column label="" width="50">
                <template slot-scope="scope">
                  <el-radio :label="scope.$index" v-model="radio" @change.native="handleSelectionChange2(scope.$index,scope.row)"></el-radio>
                </template>
              </el-table-column>
              <!--  @selection-change="handleSelectionChange2" <el-table-column type="selection" align="center" width="55"></el-table-column> -->
              <el-table-column property="name" align="center" label="服务名称"> </el-table-column>
              <el-table-column property="serviceTime" align="center" label="时长"> </el-table-column>
              <el-table-column property="price" align="center" label="价格"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer foot">
              <el-button size="small" type="primary" @click="sureservice">确 定</el-button>
              <el-button size="small" @click="cancelservice">取 消</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  saveOrUpdatetimesCard,
  serviceList,
  uploadHtml,
  timesCardDetail,
  serviceDetail
} from "@/api";
import util from '@/util'
export default {
  computed: mapState(["merchantId", "isShop", "soUrce","power"]),
  data() {
    var limitValiditydity = (rules,value, callback) => {
      // if(!value) {
      //   callback(new Error('不能输入空值'))
      // }
      if(value.length > 11) {
        callback(new Error('输入内容过长'))
      }else {
        callback()
      }
    }
    var limitPrice = (rules, value, callback) => {
      var intPart = ''
      var floatPart = ''
      var strValue = value + ''
      if(strValue.indexOf('.') > 0) {
        intPart = strValue.split('.')[0]
        floatPart = strValue.split('.')[1]
      }else {
        intPart = strValue
      }
      if(intPart.length >10) {
        callback(new Error('数值过大'))
      } else if(floatPart.length > 2) {
        callback(new Error('最多精确到小数点后两位'))
      } else {
        callback()
      }
    }
    return {
      storeyin: false,
      cikic: true,
      radio: "",
      tableData: [],
      tableDatas: [],
      serviceWidthGoods: [], //服务需要消耗的商品
      dialogVisiblew: false,
      editorContent: "",
      ruleForm: {
        ciname: "",
        climoney: "",
        termvalidity: "",
        limitofuse: "",
        participation: "",
        sales: "0",
        salesbai: "",
        salesbai1: "",
        status: "0",
        use: "",
        classOne: "",
        classTwo: "",
        classThree: "",
        originPrice:'',
        fitPerNum:'',
        checkboxGroup: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        appointmentMsg:'',
        ruleHint:'',
         isCommission: '0', // 是否设置提成
        commissionType: '0', //提成类型
        number: '', //提成金额或者百分比
        startTime: "",
        endTime: ""
      },
      defauleTime: new Date('0'),
      timeList: [],
      rules: {
        ciname: [
          { required: true, message: "请输入次卡名称", trigger: "blur" },
          { min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classOne: [
          { required: true, message: "请选择所属一级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classTwo: [
          { required: true, message: "请选择所属二级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classThree: [
          { required: true, message: "请选择所属三级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        salesbai: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validatenum,
            trigger: "blur"
          }
        ],
        salesbai1: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          }
        ],
        climoney: [
          {
            required: true,
            message: "请输入次卡会员价",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        originPrice:[
          {
            required: true,
            message: '请输入次卡原价',
            trigger: 'change'
          },
          {
            validator: util.valida,
            trigger: 'blur'
          },
          {
            validator: util.validateOperatingArea,
            trigger: 'blur'
          },
          {
            validator: util.validatenum1,
            trigger: 'blur'
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        termvalidity: [
          {
            required: true,
            message: "请输入有效期",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          },
          {
            validator: limitValiditydity,
            trigger: "blur"
          }
        ],
        limitofuse: [
          {
            required: true,
            message: "请输入有效次数",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          }
        ],
        participation: [
          { required: false, message: "请选择参与服务", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        fitPerNum: [{ required: true, message: '请选择人数', trigger: 'change' }],
        checkboxGroup:[{ required: true, message: '请选择日期', trigger: 'change' },],
        appointmentMsg: [{ required: true, message: '请输入预约信息', trigger: 'blur' },{ min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' }],
        ruleHint:[{ required: true, message: '请输入规则提醒', trigger: 'blur' },{ min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' }],
      },

      selectedOptions3: ["zujian", "data", "tag"],
      isbai: true,
      ismoney: false,
      changefuwu: [],
      options: [],
      options2: [],
      options3: [],
      fuwutiao: {},
      options: [
        {value: '0',label: '不限制'},{value: '1',label: '1人'},
        {value: '2',label: '2人'},{value: '3',label: '3人'},
        {value: '4',label: '4人'},{value: '5',label: '5人'},
        {value: '6',label: '6人'},{value: '7',label: '7人'},
        {value: '8',label: '8人'},{value: '9',label: '9人'},
        {value: '10',label: '10人'},
      ],
      value: '',
      cities: ['周一', '周二', '周三', '周四', '周五', '周六', '周日', '无'],//日期选择
      showTab:""
    };
  },
  created() {
    this.isApp = this.setRole("APP权限")
  },
  mounted() {
   this.showTab=util.getQuery('showTab')
    if(this.showTab=="2"){
        this.storeyin = true;
    }
    this.cidetail();
    },

  methods: {
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    //字符串过滤
    replace(obj, key) {
      let that = this
      let event = event || window.event
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(obj, key);
        }, 100);
      } else {
        that.validItem(obj, key);
      }
    },
    validItem(obj, key) {
      let res = ''
      switch (key) {
        case 'salesbai':
        case 'climoney':
        case 'originPrice':
          res = util.replaceNum(obj[key], 10);
          break;
      }
      this.$set(obj, key, res);
    },
    // 服务的详情
    serdetail(id) {
      let data = {
        id: id
      };
      serviceDetail(data).then(res => {
        if(res.data.goodsList){
          this.serviceWidthGoods = res.data.goodsList
        } else {
          this.serviceWidthGoods = []
        }
      });
    },
    // 次卡查询详情
    cidetail() {
      let data = {
        id: util.getQuery('cardId')
      };
      timesCardDetail(data).then(res => {
        console.log(res.data.id)
        if (res.data.id != "") {
          this.ruleForm.ciname = res.data.name;
          this.ruleForm.classOne = res.data.primaryClassification;
          this.ruleForm.classTwo = res.data.secondClassification;
          this.ruleForm.classThree = res.data.threeClassification;
          this.ruleForm.climoney = res.data.price;
          this.ruleForm.termvalidity = res.data.validDay;
          this.ruleForm.limitofuse = res.data.times;
          this.ruleForm.sales = JSON.stringify(res.data.deductType);
          this.ruleForm.originPrice = res.data.originPrice
          this.ruleForm.fitPerNum = res.data.fitPerNum
          this.ruleForm.checkboxGroup = res.data.useExcludeDate.split(',')
          this.ruleForm.appointmentMsg = res.data.appointmentMsg
          this.ruleForm.ruleHint = res.data.ruleHint
          this.ruleForm.isCommission = res.data.royalty+ ''
          this.ruleForm.commissionType = res.data.deductType + ''
          this.ruleForm.number = res.data.deductAmount
          this.timeList = res.data.timeList

          this.serviceid = res.data.servicesId;
          this.serdetail(this.serviceid)
          // var text = JSON.parse(res.data.remark);
          // this.editorContent = text.remarkText;
          // this.editor.txt.html(this.editorContent);
          var a = {
            name: res.data.servicesName,
            serviceTime: res.data.serviceTime,
            price: res.data.servicePrice
          };
          this.tableDatas.push(a);
          this.ruleForm.status = res.data.status.toString();
        }
      });
    },
    // 保存
    getContent() {
        var addci = new FormData();
        addci.append("id", util.getQuery('cardId'));
        addci.append("companyId", this.merchantId);
        addci.append("name", this.ruleForm.ciname);
        addci.append("price", this.ruleForm.climoney);
        addci.append("validDay", this.ruleForm.termvalidity);
        addci.append("times", this.ruleForm.limitofuse);
        addci.append("deductType", this.ruleForm.sales);
        if (this.ruleForm.sales == 0) {
          addci.append("deductAmount", this.ruleForm.salesbai);
        } else if (this.ruleForm.sales == 1) {
          addci.append("deductAmount", this.ruleForm.salesbai1);
        }
        addci.append("status", this.ruleForm.status);
        addci.append("serviceId", this.serviceid);
        addci.append('fitPerNum', this.ruleForm.fitPerNum)//适用人数
        addci.append('useExcludeDate', this.ruleForm.checkboxGroup)
        addci.append('appointmentMsg', this.ruleForm.appointmentMsg)
        addci.append('ruleHint', this.ruleForm.ruleHint)
        addci.append('originPrice', this.ruleForm.originPrice)
         let deductAmount
      if (this.ruleForm.sales == 0) {
        deductAmount=this.ruleForm.salesbai
      } else if (this.ruleForm.sales == 1) {
         deductAmount=this.ruleForm.salesbai1
      }
        let data={
          id:util.getQuery('cardId'),
          companyId:this.merchantId,
        name:this.ruleForm.ciname,
        price:this.ruleForm.climoney,
        validDay:this.ruleForm.termvalidity,
        times:this.ruleForm.limitofuse,
        deductType:this.ruleForm.sales,
        status:this.ruleForm.status,
        serviceId:this.serviceid,
        fitPerNum:this.ruleForm.fitPerNum,
        useExcludeDate:this.ruleForm.checkboxGroup.toString(),
        appointmentMsg:this.ruleForm.appointmentMsg,
        ruleHint:this.ruleForm.ruleHint,
        originPrice:this.ruleForm.originPrice,
        royalty: this.ruleForm.isCommission,
        deductType: this.ruleForm.commissionType,
        deductAmount: this.ruleForm.number,
        timeList: this.timeList,
        royalty: this.ruleForm.isCommission,
        deductType: this.ruleForm.commissionType,
        deductAmount: this.ruleForm.number
        }
        saveOrUpdatetimesCard(data).then(res => {
         if(res.code=="200"){
            history.back();
         }
        });
    },

    submitForm(formName) {
       if (this.ruleForm.isCommission == '1' && (!this.ruleForm.number || this.ruleForm.number == 0)) {
        this.$message.error('请输入提成值且大于0！')
        return
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.ruleForm.climoney > this.ruleForm.originPrice){
            this.$message.error('会员价格不能大于原价格')
            return
          }
          this.getContent();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.go("-1");
    },
    // 营业员提成
    moneychange(val) {
      if (val == "0") {
        this.isbai = true;
        this.ismoney = false;
      } else if (val == "1") {
        this.ismoney = true;
        this.isbai = false;
      }
    },
    // 选择服务
    // 服务的列表
    changeservice() {
      this.dialogVisiblew = true;
      let data = {
        companyId: this.merchantId
      };
      serviceList(data).then(res => {
        this.tableData = res.data;
      });
    },
    // 点击×
    serviceicon() {
      this.dialogVisiblew = false;
    },
    // 点击选中
    handleSelectionChange2(index, row) {
      this.fuwutiao = row;
    },
    // 点击确定
    sureservice() {
      this.tableDatas.push(this.fuwutiao);
      this.serdetail(this.fuwutiao.id)
      this.dialogVisiblew = false;
    },
    // 点击取消
    cancelservice() {
      this.dialogVisiblew = false;
    },
     // 添加可用时间
    onAddTime() {
      if(this.ruleForm.endTime && this.ruleForm.startTime){
        if(this.ruleForm.endTime < this.ruleForm.startTime) {
          this.$message.error("结束时间不能大于开始时间")
        } else {
          this.timeList.push({
            startTime: this.ruleForm.startTime,
            endTime: this.ruleForm.endTime
          })
          this.ruleForm.startTime = '';
          this.ruleForm.endTime = ''
        }
      }else {
        this.$message.error('请选择可用时间')
      }
    },
    //  删除可用时间
    handleClose(tag) {
      this.timeList.splice(this.timeList.indexOf(tag), 1);
    }
  }
};
</script>
<style scoped>
.el-tag {
  margin-right: 10px;
}
.from_main .el-input {
  width: 350px;
}
.wxclass .el-form-item {
  float: left;
}

.wxclass .el-form-item:nth-child(2) {
  margin-left: 10px;
}

.wxclass .el-form-item:nth-child(3) {
  margin-left: 10px;
}
/*表单的样式*/

.from_main {
    margin-top: 15px;
}

.from_main p {
    width: 100%;
    color: #444;
    font-size: 14px;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 10px;
}

.from_main .el-input {
    width: 350px;
}

.from_main .input {
    width: 200px;
}

.from_main .line {
    margin-left: 35px;
}

.from_main .el-textarea__inner {
    width: 500px;
}

.from_main .fotter_button {
    margin-left: 350px;
}
.foot{
margin-top: 20px;
    text-align: center;
}
</style>
<style>
#editorElem p {
  border-bottom: none !important;
}
.from_main .wxclass .el-input {
  width: 200px;
}
.shopname .el-radio__label {
  display: none;
}
.subcardedit .el-input-group--prepend .el-input__inner,
.el-input-group__append {
  border: solid 1px #579ff8;
  background-color: #579ff8;
  color:#fff;
}
</style>
